package cn.stylefeng.guns.modular.manager.controller;

import cn.janaker.paysdk.model.PayConstants;
import cn.janaker.paysdk.pay.ITradeClient;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.manager.entity.FlowCommissionManagement;
import cn.stylefeng.guns.modular.manager.entity.FlowMemberLog;
import cn.stylefeng.guns.modular.manager.entity.FlowWxMember;
import cn.stylefeng.guns.modular.manager.model.params.FlowWxMemberParam;
import cn.stylefeng.guns.modular.manager.service.FlowCommissionManagementService;
import cn.stylefeng.guns.modular.manager.service.FlowWxMemberService;
import cn.stylefeng.guns.modular.paytest.config.TradeClientFactory;
import cn.stylefeng.guns.modular.paytest.entity.DefaultPayConfig;
import cn.stylefeng.guns.utils.HttpBaseRequest;
import cn.stylefeng.guns.utils.redisUtil.RedisPrefixConstant;
import cn.stylefeng.guns.utils.redisUtil.RedisUtil;
import cn.stylefeng.guns.utils.weixin.AccessToken;
import cn.stylefeng.guns.utils.weixin.WeiXinConfig;
import cn.stylefeng.guns.utils.weixin.WeiXinUtil;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ijpay.core.kit.IpKit;
import com.ijpay.core.kit.PayKit;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApiConfig;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.ijpay.wxpay.model.TransferModel;
import com.ijpay.core.enums.SignType;
import com.jfinal.kit.StrKit;
import com.ijpay.wxpay.WxPayApiConfigKit;
import com.ijpay.wxpay.WxPayApi;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;


/**
 * 控制器
 *
 * @author yumker
 * @Date 2021-06-05 03:43:54
 */
@Controller
@RequestMapping("/flowWxMember")
public class FlowWxMemberController extends BaseController {

    private String PREFIX = "/manager/flowWxMember";
    private String PREFIX1 = "/manager/flowOther";

    @Autowired
    private FlowWxMemberService flowWxMemberService;

    @Autowired
    private FlowCommissionManagementService flowCommissionManagementService;

    @Autowired
    TradeClientFactory tradeClientFactory;

    @Autowired
    DefaultPayConfig defaultPayConfig;
    @Autowired
    private  RedisUtil redisUtil;
    /**
     * 跳转到主页面
     *
     * @author yumker
     * @Date 2021-06-05
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/flowWxMember.html";
    }

    @RequestMapping("/other")
    public String other() {
        return PREFIX1 + "/flowOther.html";
    }
    /**
     * 新增页面
     *
     * @author yumker
     * @Date 2021-06-05
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/flowWxMember_add.html";
    }

    @RequestMapping("/add1")
    public String add1() {
        return PREFIX1 + "/flowOther_add.html";
    }

    /**
     * 编辑页面
     *
     * @author yumker
     * @Date 2021-06-05
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/flowWxMember_edit.html";
    }

    @RequestMapping("/edit1")
    public String edit1() {
        return PREFIX1 + "/flowOther_edit.html";
    }

    /**
     * 新增接口
     *
     * @author yumker
     * @Date 2021-06-05
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(FlowWxMemberParam flowWxMemberParam) {
        this.flowWxMemberService.add(flowWxMemberParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author yumker
     * @Date 2021-06-05
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(FlowWxMemberParam flowWxMemberParam) {
        this.flowWxMemberService.update(flowWxMemberParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author yumker
     * @Date 2021-06-05
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(FlowWxMemberParam flowWxMemberParam) {
        this.flowWxMemberService.delete(flowWxMemberParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author yumker
     * @Date 2021-06-05
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(FlowWxMemberParam flowWxMemberParam) {
        FlowWxMember detail = this.flowWxMemberService.getById(flowWxMemberParam.getMemberId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author yumker
     * @Date 2021-06-05
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(FlowWxMemberParam flowWxMemberParam) {
        return this.flowWxMemberService.findPageBySpec(flowWxMemberParam);
    }

    @ResponseBody
    @RequestMapping("/list1")
    public LayuiPageInfo list1(FlowWxMemberParam flowWxMemberParam) {
        flowWxMemberParam.setOneAuthority("1");
        return this.flowWxMemberService.findPageBySpec(flowWxMemberParam);
    }

    //获取二维码
//    @RequestMapping("/getQrCode")
//    @ResponseBody
//    public ResponseData getQrCode(HttpServletRequest request){
//        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
//        String parm = baseRequest.getString("parm");
//        String memberId = baseRequest.getString("memberId");
//
//        String token= WeiXinUtil.getToken();
//        String path=this.getClass().getResource("/").getPath()+"uploadFiles/QrCode/"+"Code"+memberId+".png";
//        System.out.println("SSSSSSSSSSSSSSS"+path);
//        byte[] bytes=WeiXinUtil.getQrCode(token,parm,path);
//        return ResponseData.success(bytes);
//    }

    @RequestMapping("/getOfficeUnionid")
    @ResponseBody
//    @GetMapping("/getOfficeUnionid")
    public ResponseData getOfficeUnionid(@RequestParam() String code){

        try {
            Map<String,String> map=WeiXinUtil.getOfficeUnionid(code);
//            AccessToken ret=WeiXinUtil.GetAccess_Token(code);
            String openid=map.get("openid");
            QueryWrapper<FlowWxMember> flowWxMemberQueryWrapper = new QueryWrapper<>();
            flowWxMemberQueryWrapper.eq("wx_unionid",map.get("unionid"));
            FlowWxMember flowWxMember=flowWxMemberService.getOne(flowWxMemberQueryWrapper);
            if(flowWxMember==null){
                return ResponseData.error("未注册小程序");

            }else {
                flowWxMember.setTemplateOpenid(openid);
                flowWxMemberService.updateById(flowWxMember);
                return ResponseData.success(openid);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseData.success();
    }

    @RequestMapping("/examine")
    @ResponseBody
    public ResponseData examine(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        String memberId = baseRequest.getString("memberId");
        QueryWrapper<FlowWxMember> flowWxMemberQueryWrapper = new QueryWrapper<>();
        flowWxMemberQueryWrapper.eq("member_id",memberId);
        flowWxMemberQueryWrapper.last("limit 1");
        FlowWxMember flowWxMember = flowWxMemberService.getOne(flowWxMemberQueryWrapper);

        if (flowWxMember!=null){
            flowWxMember.setOneAuthority("1");
            flowWxMemberService.updateById(flowWxMember);

            //建立佣金系统
            FlowCommissionManagement flowCommissionManagement=new FlowCommissionManagement();
            flowCommissionManagement.setOnlySign(1l);
            flowCommissionManagement.setUserId(flowWxMember.getMemberId().toString());
            flowCommissionManagementService.save(flowCommissionManagement);

        }
        return ResponseData.success(flowWxMember);
    }

    /**
     * 企业付款到零钱
     */
    @RequestMapping("/transfer")
    @ResponseBody
    public ResponseData transfer(HttpServletRequest request, @RequestParam("userId") String userId, BigDecimal applyDrawPrice,Integer commissionId) {

        String ip = IpKit.getRealIp(request);
        if (StrKit.isBlank(ip)) {
            ip = "127.0.0.1";
        }


        if(!StringUtils.isEmpty(redisUtil.get(RedisPrefixConstant.WX_WITHDRAWAL_INTERVAL_SIGN))&&
                redisUtil.get(RedisPrefixConstant.WX_WITHDRAWAL_INTERVAL_SIGN).toString().equals(userId)){


            return ResponseData.error("请勿重复操作");
        }else {
            redisUtil.set(RedisPrefixConstant.WX_WITHDRAWAL_INTERVAL_SIGN, userId, 300);
        }

        QueryWrapper<FlowWxMember> flowWxMemberQueryWrapper = new QueryWrapper<>();
        flowWxMemberQueryWrapper.eq("member_id",userId);
        FlowWxMember flowWxMember=flowWxMemberService.getOne(flowWxMemberQueryWrapper);

        String appid= WeiXinConfig.sAppID;
        //

//        ITradeClient tradeClient = tradeClientFactory.getClient("defaultPay");
//        WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getApiConfig(appid);

        System.out.println("getAppID:"+defaultPayConfig.getAppID());
        Map<String, String> params = TransferModel.builder()
                .mch_appid(defaultPayConfig.getAppID())
                .mchid(defaultPayConfig.getMchID())
                .nonce_str(PayKit.generateStr())
                .partner_trade_no(PayKit.generateStr())
                .openid(flowWxMember.getWxOpenid())
                .check_name("NO_CHECK")
                .amount(applyDrawPrice.multiply(new BigDecimal(100)).setScale(0, RoundingMode.HALF_UP).toString())
                .desc("提现")
                .spbill_create_ip(ip)
                .build()
                .createSign(defaultPayConfig.getKey(), SignType.MD5, false);

        // 提现
        String transfers = WxPayApi.transfers(params, defaultPayConfig.getCertPath(), defaultPayConfig.getMchID());
//        log.info("提现结果:" + transfers);
        Map<String, String> map = WxPayKit.xmlToMap(transfers);
        String returnCode = map.get("return_code");
        String resultCode = map.get("result_code");
        if (WxPayKit.codeIsOk(returnCode) && WxPayKit.codeIsOk(resultCode)) {
            // 提现成功
            QueryWrapper<FlowCommissionManagement> flowCommissionManagementQueryWrapper = new QueryWrapper<>();
            flowCommissionManagementQueryWrapper.eq("user_id",userId);
            flowCommissionManagementQueryWrapper.eq("only_sign",1l);
            FlowCommissionManagement flowCommissionManagementOne=flowCommissionManagementService.getOne(flowCommissionManagementQueryWrapper);
            BigDecimal res=flowCommissionManagementOne.getDrawPrice().add(applyDrawPrice);
            flowCommissionManagementOne.setDrawPrice(res);
            flowCommissionManagementService.updateById(flowCommissionManagementOne);

            QueryWrapper<FlowCommissionManagement> flowCommissionManagementQueryWrapper1 = new QueryWrapper<>();
            flowCommissionManagementQueryWrapper1.eq("user_id",userId);
            flowCommissionManagementQueryWrapper1.eq("only_sign",3l);
            flowCommissionManagementQueryWrapper1.eq("commission_id",commissionId);
            FlowCommissionManagement flowCommissionManagementTwo=flowCommissionManagementService.getOne(flowCommissionManagementQueryWrapper1);
            flowCommissionManagementTwo.setDrawSign(1l);
            flowCommissionManagementService.updateById(flowCommissionManagementTwo);
            return ResponseData.success(null);
        } else {
            // 提现失败
            return ResponseData.error(map.get("err_code_des"));
        }
        //return transfers;
    }

}


